package com.itheima.service;

import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringSecurityUserService implements UserDetailsService {
    //模拟数据库中的用户数据
    public  static Map<String, User> map = new HashMap<>();
    static {
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("admin");//明文密码（没有加密）

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword("1234");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        //根据用户名去数据库里面查询这个用户的信息,这里是模拟的数据库信息,用的静态代码块
        User user = map.get(username);
        if(user==null){
            //就是不存在,直接返回null,这样框架就会知道,不正确,从而重新登录
            return null;
        }else{
            //存在,我们就个这个用户授予权限和角色
            List<GrantedAuthority>list=new ArrayList<>();
            //这个是授予权限
            list.add(new SimpleGrantedAuthority("permission_a"));
            //这个是授予角色
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username,
                    "{noop}" + user.getPassword(), list);
            return user1;
        }
    }
}
